package com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.base.dto.PaginatedQueryDTO;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.AttendantProviderService;
import com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.InsuranceService;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.InsuranceDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.integration.dao.InsuranceDao;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.Constants;
import com.paic.pafa.app.biz.service.BaseService;
import com.paic.pafa.app.biz.service.BusinessServiceException;

/**
 * 医保服务人员Service实现类
 * 
 * @author EX-LUORONG001
 * 
 */
@Service("insuranceService")
public class InsuranceServiceImpl extends BaseService implements
		InsuranceService {

	private Log log = LogFactory.getLog(this.getClass());

	@Autowired
	private CommonDAO commonDAO;
	
	@Autowired
	private InsuranceDao insuranceDao;

	@Autowired
	private AttendantProviderService attendantProviderService;

	@Override
	public int queryContactCount(Map<String, Object> map)
			throws BusinessServiceException {
		int count = 0;
		try {
			count = (int) commonDAO.count("healthcare.getInsuranceListCounts",
					map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public List getInsuranceList(int start, int limit, Map<String, Object> param)
			throws BusinessServiceException {
		PaginatedQueryDTO dto = new PaginatedQueryDTO();
		dto.setStart(start);
		dto.setLimit(limit);
		dto.setParam(param);
		return commonDAO.query("healthcare.getInsuranceList", dto);
	}

	@Override
	@Transactional
	public Map<String, Object> addContact(JSONObject transferJson)
			throws BusinessServiceException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			InsuranceDTO contactDTO = null;
			String region = transferJson.getString("region");
			contactDTO = JSONObject.toJavaObject(transferJson,
					InsuranceDTO.class);
			String guid = commonDAO.getUUID();
			// 从规则编码表获取人员编号
			Map<String, String> queryMap = new HashMap<String, String>();
			queryMap.put("region", region);
			queryMap.put("type", "0");
			String code = (String) commonDAO.get("healthcare.getRuleCode",
					queryMap);
			String createdBy = contactDTO.getCreatedBy();
			String updatedBy = contactDTO.getUpdatedBy();
			String jobAddr = contactDTO.getJobAdder();
			contactDTO.setCode(code);

			List<String> jobAddrList = clearRepeat(jobAddr.split(","));
			if (jobAddrList != null && !jobAddrList.isEmpty()) {
				// 格式providerCode|pepartNo,providerCode|pepartNo
				// String[] jobAddrs = jobAddr.split(",");
				for (int i = 0; i < jobAddrList.size(); i++) {
					Map temp = new HashMap<String, String>();
					String providerCode = jobAddrList.get(i).split("\\|")[0];
					String departNo = jobAddrList.get(i).split("\\|")[1];
					temp.put("insuranceid", code);
					temp.put("providerid", providerCode);
					temp.put("departNo", departNo);
					temp.put("createdBy", createdBy);
					temp.put("updatedBy", updatedBy);
					commonDAO.insert("healthcare.addJobAddr", temp);
				}
			}

			contactDTO.setId(guid);
			
			//remove repeat start
			List<Map<String,Object>> list=insuranceDao.getAll();
			String oneStr= contactDTO.getName()+contactDTO.getInsurancenum()+contactDTO.getCertificateType()+contactDTO.getCertificateNo();
			for(Map<String,Object> map:list)
			{
				String anOther=(String)map.get("name")+map.get("insuranceNum")+map.get("certificateType")+map.get("certificateNo");
				if(oneStr!=null&&oneStr.equals(anOther))
				{
					result.put("message","已经存在相同数据。");
					return result;
				}
			}
			
			commonDAO.insert("healthcare.addInsurance", contactDTO);
			// 更新编码规则表的num+1
			commonDAO.update("healthcare.updateRuleCode", queryMap);
			result.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			result.put(Constants.MSG_KEY, Constants.INSERT_SUCCESS);
		} catch (Exception e) {
			log.error("update insurance info error", e);
		}
		return result;
	}

	@Override
	@Transactional
	public Map<String, Object> updateContact(JSONObject transferJson)
			throws BusinessServiceException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			InsuranceDTO contactDTO = null;
			JSONArray ja = (JSONArray) transferJson.remove("updateList");
			if (null != ja && ja.size() != 0) {
				for (int i = 0; i < ja.size(); i++) {
					JSONObject tempJb = ja.getJSONObject(i);
					tempJb.put("createdBy", transferJson.get("updatedBy"));
					tempJb.put("updatedBy", transferJson.get("updatedBy"));
					attendantProviderService.addChangeRecord(tempJb);
				}
			}

			contactDTO = JSONObject.toJavaObject(transferJson,
					InsuranceDTO.class);
			String code = contactDTO.getCode();
			String createdBy = contactDTO.getUpdatedBy();
			String updatedBy = contactDTO.getUpdatedBy();
			
			//防止重复。
			List<Map<String,Object>> list=insuranceDao.getAll();
			String oneStr= contactDTO.getName()+contactDTO.getInsurancenum()+contactDTO.getCertificateType()+contactDTO.getCertificateNo();
			for(Map<String,Object> map:list)
			{
				String anOther=(String)map.get("name")+map.get("insuranceNum")+map.get("certificateType")+map.get("certificateNo");
				if(oneStr!=null&&oneStr.equals(anOther))
				{
					result.put("message","已经存在相同数据。");
					return result;
				}
			}
			// 删除原有的地址
			commonDAO.update("healthcare.deleteWorkAddr", code);

			// 新增现在地址
			String jobAddr = contactDTO.getJobAdder();
			List<String> jobAddrList = clearRepeat(jobAddr.split(","));
			if (jobAddrList != null && !jobAddrList.isEmpty()) {
				// 格式providerCode|pepartNo,providerCode|pepartNo
				// String[] jobAddrs = jobAddr.split(",");
				for (int i = 0; i < jobAddrList.size(); i++) {
					Map temp = new HashMap<String, String>();
					String providerCode = jobAddrList.get(i).split("\\|")[0];
					String departNo = jobAddrList.get(i).split("\\|")[1];
					temp.put("insuranceid", code);
					temp.put("providerid", providerCode);
					temp.put("departNo", departNo);
					temp.put("createdBy", createdBy);
					temp.put("updatedBy", updatedBy);
					commonDAO.insert("healthcare.addJobAddr", temp);
				}
			}
			commonDAO.update("healthcare.updateInsurance", contactDTO);
			result.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			result.put(Constants.MSG_KEY, Constants.UPDATE_SUCCESS);
		} catch (Exception e) {
			log.error("add insurance info error", e);
		}
		return result;
	}

	private List<String> clearRepeat(String[] jobAddr2) {
		List<String> sList = new ArrayList<String>();
		for (String jobAddr : jobAddr2) {
			if (!sList.contains(jobAddr) && jobAddr.matches(".+\\|.+")) {
				sList.add(jobAddr);
			}
		}

		return sList;
	}

	@Override
	public Map<String, Object> queryContactList(int start, int limit,
			Map<String, Object> param) throws BusinessServiceException {
		PaginatedQueryDTO dto = new PaginatedQueryDTO();
		dto.setStart(start);
		dto.setLimit(limit);
		dto.setParam(param);
		return commonDAO.queryPage("healthcare.getInsuranceList", dto);
	}

	@Override
	public Map<String, Object> queryHealthDetail(String providerid)
			throws BusinessServiceException {
		Map<String, Object> result = null;
		try {
			result = (Map<String, Object>) commonDAO.get(
					"healthcare.queryHealthDetail", providerid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public Map<String, Object> queryContactDetail(String id)
			throws BusinessServiceException {
		Map<String, Object> result = null;
		List resultList = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 查询人员信息的详情，然后根据详情中的code取查询人员对应的机构信息
			result = (Map<String, Object>) commonDAO.get(
					"healthcare.queryInsuranceDetail", id);
			String code = (String) result.get("code");
			resultList = commonDAO.query("healthcare.queryInstitutionList",
					code);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
			result.put("institutionList", resultList);
			resultMap.put(Constants.SUCCESS_RESULT_KEY, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> deleteContact(JSONObject transferJson)
			throws BusinessServiceException {
		Map<String, String> parms = new HashMap<String, String>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String id = transferJson.getString("ids");
			String ids = "";
			if (null != id && !"".equals(id)) {
				ids = id.substring(0, id.length() - 1);
			}
			parms.put("ids", ids);
			parms.put("updatedBy", transferJson.getString("updatedBy"));
			commonDAO.update("healthcare.deleteInsurance", parms);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.DELETE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
}
